package com.itcs.app.service.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.itcs.app.service.ItcsTraderecordsService;
import com.itcs.app.tran.SendBoxSocket;
import com.itcs.app.util.ParamMap;
import com.itcs.app.util.StringUtils;
import com.itcs.box.domain.BoxResponse;
import com.itcs.box.util.BoxResUtils;
import com.itcs.box.util.LogUtils;
import com.itcs.rongyun.rongsdk.Response;
import com.itcs.trading.mapper.ExitWhitelistOpHisMapper;
import com.itcs.trading.mapper.TerminalInfoMapper;
import com.itcs.trading.mapper.UserCarInfoMapper;
import com.itcs.trading.model.ExitWhitelistOpHis;
import com.itcs.trading.model.TerminalInfo;
import com.itcs.trading.model.UserCarInfo;

/**
 * @author LiuPeng
 * @date 2017年12月21日
 * 
 */
@Service("itcsTraderecordsService")
public class ItcsTraderecordsServiceImpl implements ItcsTraderecordsService {

	private Log logger = LogFactory.getLog(getClass());

	@Autowired
	private TerminalInfoMapper terminalInfoMapper;

	@Autowired
	private UserCarInfoMapper userCarInfoMapper;

	// 白名单
	@Autowired
	private ExitWhitelistOpHisMapper exitWhitelistOpHisMapper;

	@Autowired
	private SendBoxSocket sendBoxSocket;

	/**
	 * 发起出口白名单
	 */
	public Response sendExitWhitelist(ParamMap param) {
		try {
			logger.info(LogUtils.build("2005", "发起出口白名单", "", JSON.toJSONString(param)));
			// 1、获取USER-ID、广场号
			Long userId = param.getLong("userId");
			String tollPlazaId = param.getString("tollstationId");
			if (userId == null || StringUtils.isEmpty(tollPlazaId)) {
				logger.warn(LogUtils.build("2005", "发起出口白名单", "用户userId 或 广场号 为空，" + JSON.toJSONString(param)));
				return Response.ERROR();
			}
			// 2、通过Userid找到车牌号/车辆信息
			UserCarInfo paramPlate = new UserCarInfo();
			paramPlate.setUserId(userId);
			paramPlate.setIsCheck(2);
			paramPlate.setDel(2);
			List<UserCarInfo> listPlate = userCarInfoMapper.findUserCarByPlateOrUserId(paramPlate);
			if (listPlate.size() < 1) {
				logger.warn(LogUtils.build("2005", "发起出口白名单", "找不到用户，异常退出：userid" + userId));
				return Response.ERROR();
			}
			// 3、tollstation收费站找所有盒子
			TerminalInfo terminalInfo = new TerminalInfo();
			terminalInfo.setTollPlazaId(tollPlazaId);
			List<TerminalInfo> terminals = terminalInfoMapper.findTerminalByTollstationId(terminalInfo);

			// 4、通过USERID，清空旧的USERID、盒子
			ExitWhitelistOpHis exitWhitelistOpHis = new ExitWhitelistOpHis();
			exitWhitelistOpHis.setUserId(userId);
			exitWhitelistOpHis.setStationId(tollPlazaId);
			exitWhitelistOpHisMapper.deleteWhitelis(exitWhitelistOpHis);
			// 5、记录是否在线，新存储USERID、车牌、盒子等信息为新白名单，存储入库
			String carPlateStr = "";
			String plateColorStr = "";
			String carClassStr = "";
			for (int i = 0; i < listPlate.size(); i++) {
				// 创建白名单
				ExitWhitelistOpHis whitelist = new ExitWhitelistOpHis();
				// whitelist.setState(0);
				whitelist.setCreateTime(new Date());
				// whitelist.set
				whitelist.setUserId(userId);
				UserCarInfo plate = listPlate.get(i);// 车牌号
				whitelist.setCarPlate(plate.getPlate());
				//TODO 不再存储收费站id，存储收费广场id，字段先不改
				whitelist.setStationId(tollPlazaId);
				Integer palteColor = plate.getPlateColor();
				whitelist.setPlateColor(palteColor == null ? null : palteColor.byteValue());// 车牌颜色??
				Integer carClass = plate.getCarClass();
				whitelist.setCarClass(carClass == null ? null : carClass.byteValue());// 车型??
				exitWhitelistOpHisMapper.insert(whitelist);

				if (i > 0) {
					carPlateStr += "," + plate.getPlate();
					plateColorStr += "," + plate.getPlateColor();
					carClassStr += "," + plate.getCarClass();
				} else {
					carPlateStr = plate.getPlate();
					plateColorStr = String.valueOf(plate.getPlateColor());
					carClassStr = String.valueOf(plate.getCarClass());
				}
			}
			// 将车牌下发给盒子
			logger.info(LogUtils.build("2005", "发起出口白名单", "carPlateStr:" + carPlateStr + ",plateColorStr:"
					+ plateColorStr + ",carClassStr:" + carClassStr + ",tollPlazaId:" + tollPlazaId));

			for (int i = 0; i < terminals.size(); i++) {
				TerminalInfo terminal = terminals.get(i);
				BoxResponse response2005 = BoxResUtils.build2005(String.valueOf(terminal.getTerminalNo()),
						String.valueOf(listPlate.size()), carPlateStr, plateColorStr, carClassStr);
				sendBoxSocket.pubsubRes2BoxServer(response2005);
			}
		} catch (Exception e) {
			logger.error(LogUtils.build("2005", "发起出口白名单", "处理异常"), e);
			return Response.ERROR();
		}
		logger.info(LogUtils.build("2005", "发起出口白名单", "白名单上传完成"));
		return Response.OK();
	}
}
